//
//  SegmentSuperViewController.m
//  SegmentPage

#import "SegmentSuperViewController.h"
#import "RWGoodsContentViewController.h"
#import "RWGoodsSPECViewController.h"
#import "MainTouchTableTableView.h"
#import "RWDetailPageHeaderView.h"
#import "MYSegmentView.h"


#import "RWGoodsDetailModel.h"
#import "AppDelegate.h"

@interface SegmentSuperViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, assign) BOOL canScroll;
@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabView;
@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabViewPre;
@property (nonatomic, strong) MainTouchTableTableView *tableView;
@property (nonatomic, strong) MYSegmentView *segmentView;
@property (nonatomic, strong) UILabel *sumLab;//小圆点
@property (nonatomic, strong) RWDetailPageHeaderView *headerView;
@property (nonatomic, assign) CGFloat alphaMemory;

@property (nonatomic, copy) RWGoodsDetailInfoModel *goodsInfoModel;
@property (nonatomic, copy) NSArray *contents;
@property (nonatomic, copy) NSArray *specs;

@end

static CGFloat const headViewHeight = 330.f;
static CGFloat const _bottomViewHeight = 50.;
#define KWidth [UIScreen mainScreen].bounds.size.width
#define KHeight [UIScreen mainScreen].bounds.size.height

@implementation SegmentSuperViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self initObjects];
    [self loadData];
    [self configNotification];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Load Datas

- (void)initObjects{

    _goodsInfoModel = [[RWGoodsDetailInfoModel alloc] init];
    _contents = [NSArray array];
    _specs = [NSArray array];
}

- (void)loadData{

    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=goodsinfo&member_id=%@&goods_id=%@", [FTYUser sharedUser].userID, _goodsID] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            NSLog(@"success=====%@", result);
            FTYErrorInfoModel *errModel = [FTYErrorInfoModel mj_objectWithKeyValues:[result objectForKey:@"err"]];
            if (0 == errModel.errorcode) {
                
                RWGoodsDetailModel *info = [RWGoodsDetailModel mj_objectWithKeyValues:[result objectForKey:@"info"]];
                _goodsInfoModel = [RWGoodsDetailInfoModel mj_objectWithKeyValues:info.goods_info];
                _contents = info.content;
                _specs = info.spec;
                
                [self setNavigation];
                [self setGoodsDetailUI];
                
            } else {
            
                [[FTYToastView alloc] addTitle:errModel.errorinfo addView:self.view];
            }
        } else {
            NSLog(@"error=====%@", error);
        }
    }];
}
//加入收藏
- (void)addFavorByGoodsId:(NSString *)gid
{
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=goodscoll&member_id=%@&goods_id=%@", [FTYUser sharedUser].userID, _goodsID] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            NSLog(@"success=====%@", result);
            FTYErrorInfoModel *errModel = [FTYErrorInfoModel mj_objectWithKeyValues:[result objectForKey:@"err"]];
            if (0 == errModel.errorcode) {
                
                _goodsInfoModel.is_coll = @"1";
                FTYButton *btn = (FTYButton *)[self.view viewWithTag:300];
                
                [btn setImage:[UIImage imageNamed:@"collect_sel_bj_icon-"] forState:UIControlStateNormal];
                [[FTYToastView alloc] addTitle:@"收藏成功" addView:self.view];
                
            } else {
                
                [[FTYToastView alloc] addTitle:errModel.errorinfo addView:self.view];
            }
        } else {
            NSLog(@"error=====%@", error);
        }
    }];
}

//取消收藏
- (void)cancelFavorByGoodsId:(NSString *)gid
{
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=cancelcoll&member_id=%@&goods_id=%@", [FTYUser sharedUser].userID, _goodsID] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            NSLog(@"success=====%@", result);
            FTYErrorInfoModel *errModel = [FTYErrorInfoModel mj_objectWithKeyValues:[result objectForKey:@"err"]];
            if (0 == errModel.errorcode) {
                
                _goodsInfoModel.is_coll = @"0";
                FTYButton *btn = (FTYButton *)[self.view viewWithTag:300];
                
                [btn setImage:[UIImage imageNamed:@"collect_bj_icon"] forState:UIControlStateNormal];
                [[FTYToastView alloc] addTitle:@"取消收藏" addView:self.view];
                
            } else {
                
                [[FTYToastView alloc] addTitle:errModel.errorinfo addView:self.view];
            }
        } else {
            NSLog(@"error=====%@", error);
        }
    }];
}



#pragma mark - Private Invoke Method

- (void)setNavigation{
    
    self.navigationItem.title = @"商品详情";
}

- (void)setGoodsDetailUI{

    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = [self headerView];
    [self setBottomUI];
}

- (RWDetailPageHeaderView *)headerView{
    
    if (_headerView == nil)
    {
        _headerView = [[RWDetailPageHeaderView alloc] initWithFrame: CGRectMake(0, 0 , KWidth,headViewHeight*FTY_WIDTH_BASE)];
        [_headerView loadDataWithModel:_goodsInfoModel];
        _headerView.userInteractionEnabled = YES;
    }
    return _headerView;
}


- (UITableView *)tableView{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (!_tableView) {
        
        _tableView = [[MainTouchTableTableView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight - _bottomViewHeight*FTY_HEIGHT_BASE) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = KHeight;
    }
    return _tableView;
}

- (void)setBottomUI{
    
    UIView *bottomV = [[UIView alloc] init];
    [self.view addSubview:bottomV];
    [bottomV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_offset(0);
        make.height.mas_offset(_bottomViewHeight*FTY_HEIGHT_BASE);
    }];
    
    NSArray *images = @[@"collect_bj_icon", @"shop_bj_icon"];
    NSArray *titles = @[@"加入收藏", @"购物车"];
    CGFloat btnW = FTY_SCREEN_WIDTH/3;
    
    for (int i=0; i<2; i++) {
        
        FTYButton *button = [FTYButton createButtonWithImage:[UIImage imageNamed:images[i]] imageEdgeInsets:UIEdgeInsetsMake(0, -8*FTY_WIDTH_BASE, 0, 0) title:titles[i]  tColor:[UIColor blackColor] titileEdgeInsets:UIEdgeInsetsMake(0, 8*FTY_WIDTH_BASE, 0, 0) fontSize:15.*FTY_WIDTH_BASE backGroundColor:[UIColor whiteColor]];
        button.tag = 300+i;
        [button addTarget:self action:@selector(bottomBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [bottomV addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.mas_offset(0);
            make.left.mas_equalTo(0 + i*btnW);
            make.width.mas_equalTo(btnW);
        }];
        
        UIView *line = [[UIView alloc] init];
        [button addSubview:line];
        line.backgroundColor = [UIColor grayColor];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.right.mas_equalTo(0);
            make.width.mas_equalTo(.5*FTY_WIDTH_BASE);
        }];
        if (i==1) {
            //购物车小圆点
            UILabel *sumLab = [[UILabel alloc] initWithFrame:CGRectMake(btnW/3-5, 5, 20, 13)];
            [button addSubview:sumLab];
            sumLab.backgroundColor  = [FTYColor getMainColorWithAlpha:1.];
            sumLab.textAlignment = NSTextAlignmentCenter;
            sumLab.font = FTY_FONTTSIZE(13);
            sumLab.textColor = [UIColor whiteColor];
            sumLab.layer.masksToBounds = YES;
            sumLab.layer.cornerRadius = 6.;
            sumLab.hidden = YES;
            _sumLab = sumLab;
        }
        
    }
    
    /*
    FTYButton *buyBtn = [FTYButton createButtonWithTitle:@"立即购买" tColor:[UIColor whiteColor] fontSize:15.*FTY_WIDTH_BASE backGroundColor:[FTYColor getMainColorWithAlpha:1.]];
    [buyBtn addTarget:self action:@selector(buyNow:) forControlEvents:UIControlEventTouchUpInside];
    [bottomV addSubview:buyBtn];
    [buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.mas_offset(0);
        make.width.mas_equalTo(btnW);
    }];
     */
    FTYButton *buyBtn = [FTYButton createButtonWithTitle:@"加入购物车" tColor:[UIColor whiteColor] fontSize:15.*FTY_WIDTH_BASE backGroundColor:[FTYColor getMainColorWithAlpha:1.]];
    [buyBtn addTarget:self action:@selector(addToShoppingCart:) forControlEvents:UIControlEventTouchUpInside];
    [bottomV addSubview:buyBtn];
    [buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.mas_offset(0);
        make.width.mas_equalTo(btnW);
    }];
    
    //根据商品详情 设置收藏按钮状态
    
    FTYButton *btn = (FTYButton *)[self.view viewWithTag:300];
    if ([_goodsInfoModel.is_coll isEqualToString:@"0"]) {
        
        [btn setImage:[UIImage imageNamed:@"collect_bj_icon"] forState:UIControlStateNormal];
    }else if ([_goodsInfoModel.is_coll isEqualToString:@"1"]){
        
        [btn setImage:[UIImage imageNamed:@"collect_sel_bj_icon-"] forState:UIControlStateNormal];
    }
    
   
}

#pragma mark - button 监听事件
//根据btn tag 判断监听 300 加入收藏，301 加入购物车
- (void)bottomBtnPressed:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    if (btn.tag==300) {
        [self addFavorOrCancel:sender];
    }else if (btn.tag==301){
        //[self addToShoppingCart:sender];
        //先回到根视图
        [self.navigationController popToRootViewControllerAnimated:NO];
        //跳转到购物车页面
        [sharedDelegate.tabBarController selectIndex:3];
    }
}
//加入收藏/取消收藏
- (void)addFavorOrCancel:(id)sender
{
    NSLog(@"SegmentSuperViewController:addToFavor 加入收藏Btn Pressed!");
    if ([_goodsInfoModel.is_coll isEqualToString:@"0"]) {
        [self addFavorByGoodsId:nil];
    }else if ([_goodsInfoModel.is_coll isEqualToString:@"1"]){
        [self cancelFavorByGoodsId:nil];
    }
    
   [[NSNotificationCenter defaultCenter] postNotificationName:@"CollectionNotification" object:nil]; 
}
//加入购物车
- (void)addToShoppingCart:(id)sender
{
    NSLog(@"SegmentSuperViewController:addToCart 加入购物车Btn Pressed!");
//    [FTYShoppingCartPort requestShoppingCartWithProjectID:_goodsID viewController:self block:^(BOOL isBool) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"AddShopCartNumberNotification" object:nil];
//    }];
    [FTYShoppingCartPort addShoppingCartWithProjectID:_goodsID viewController:self block:^(BOOL isBool) {
        //[[NSNotificationCenter defaultCenter] postNotificationName:@"AddShopCartNumberNotification" object:nil];
    }];
}


//立即购买
- (void)buyNow:(id)sender
{
    NSLog(@"SegmentSuperViewController:buyNow: 立即购买Btn Pressed!");
}
#pragma mark - Config Notification

- (void)configNotification{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(leaveTop:) name:@"leaveTop" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addShopCartNumber) name:@"AddShopCartNumberNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(firstShowShopCartNumber:) name:@"TabbarShopCartNumberShowNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(minusShopCartNumber:) name:@"MinusShopCartNumberNotification" object:nil];
}



#pragma mark - Notificaiton Invoke Methods

- (void)leaveTop:(NSNotification *)notification{
    
    NSDictionary *userInfo = notification.userInfo;
    NSString *canScroll = userInfo[@"canScroll"];
    if ([canScroll isEqualToString:@"1"]) {
        _canScroll = YES;
    }
}

- (void)addShopCartNumber{
    
    NSInteger sum = [self.sumLab.text integerValue];
    self.sumLab.hidden = NO;
    self.sumLab.text = [@(sum + 1) stringValue];
}

- (void)firstShowShopCartNumber:(NSNotification *)notify{
    
    NSInteger sum = [notify.object[@"number"] integerValue];
    if (sum > 0) {
        self.sumLab.hidden = NO;
    } else {
        self.sumLab.hidden = YES;
    }
    self.sumLab.text = [notify.object[@"number"] stringValue];
}

- (void)minusShopCartNumber:(NSNotification *)notify{
    
    NSInteger minusSum = [notify.object[@"number"] integerValue];
    NSInteger oldSum = [self.sumLab.text integerValue];
    NSInteger newSum = oldSum - minusSum;
    self.sumLab.text = [@(newSum) stringValue];
}




#pragma mark - <UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.contentView addSubview:self.segmentView];
    return cell;
}

- (UIView *)segmentView
{
    if(!_segmentView){
        
        RWGoodsContentViewController *goodsContentVC = [[RWGoodsContentViewController alloc] init];
        [goodsContentVC loadDataWithContents:_contents];
        RWGoodsSPECViewController *goodsSPECVC = [[RWGoodsSPECViewController alloc] init];
        [goodsSPECVC loadDataWithSPECs:_specs];
        
        NSArray *controllerArray = @[goodsContentVC, goodsSPECVC];
        NSArray *titleArray = @[@"图文详情", @"规格参数"];
        
        CGFloat lineWidth = [@"图文详情" boundingRectWithSize:CGSizeMake(200, 21) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0f*FTY_HEIGHT_BASE]} context:nil].size.width;
        
        MYSegmentView *tempView = [[MYSegmentView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight) controllers:controllerArray titleArray:titleArray ParentController:self lineWidth:lineWidth lineHeight:3.];
        _segmentView = tempView;
        
        //中间分割线 TODO:将写到segmentView内部去，实现根据标题个数自动加载相应数量的分割线
        UIView *cutLine = [[UIView alloc] init];
        [tempView addSubview:cutLine];
        cutLine.backgroundColor = [UIColor grayColor];
        [cutLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.left.mas_equalTo(FTY_SCREEN_WIDTH/2);
            make.width.mas_equalTo(.5*FTY_WIDTH_BASE);
            make.height.mas_equalTo(47.*FTY_HEIGHT_BASE);
        }];
    }
    return _segmentView;
}

#pragma mark - <UITableViewDelegate>

#pragma mark - <UIScrollViewDelegate>

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    /**
     * 处理联动
     */
    //获取滚动视图y值的偏移量

    CGFloat offsetY = scrollView.contentOffset.y;//注意
//    NSLog(@"lff===%f", offsetY);
    
    CGFloat xoffset = (offsetY + headViewHeight)/2;
    if (offsetY < -headViewHeight) {
        CGRect f = self.headerView.frame;
        f.origin.y = offsetY;
        f.size.height = -offsetY;
        f.origin.x = xoffset;
        f.size.width = KWidth + fabs(xoffset)*2;
        self.headerView.frame = f;
    }
   
    
    CGFloat tabOffsetY = [_tableView rectForSection:0].origin.y;
    _isTopIsCanNotMoveTabViewPre = _isTopIsCanNotMoveTabView;
    if (offsetY >= tabOffsetY) {
        //不能滑动
        scrollView.contentOffset = CGPointMake(0, tabOffsetY);
        _isTopIsCanNotMoveTabView = YES;
        
    }else{
        
        //可以滑动
        _isTopIsCanNotMoveTabView = NO;
        
    }
    if (_isTopIsCanNotMoveTabView != _isTopIsCanNotMoveTabViewPre) {
        
        if (!_isTopIsCanNotMoveTabViewPre && _isTopIsCanNotMoveTabView) {
            //NSLog(@"子视图控制器滑动到顶端");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"goTop" object:nil userInfo:@{@"canScroll":@"1"}];
            _canScroll = NO;
        }
        if(_isTopIsCanNotMoveTabViewPre && !_isTopIsCanNotMoveTabView){
            //NSLog(@"父视图控制器滑动到顶端");
            if (!_canScroll) {
                
                scrollView.contentOffset = CGPointMake(0, tabOffsetY);
            }
        }
    }
    
    
}

@end
